// utils/crypto-helper.js
// 微信小程序兼容的加密工具类

class CryptoHelper {
  constructor() {
    // 初始化加密工具
  }

  // SHA256哈希函数（简化实现）
  sha256(data) {
    // 这是一个简化的SHA256实现
    // 在实际项目中，建议使用成熟的加密库
    let hash = 0
    for (let i = 0; i < data.length; i++) {
      const char = data.charCodeAt(i)
      hash = ((hash << 5) - hash) + char
      hash = hash & hash // Convert to 32bit integer
    }
    return Math.abs(hash).toString(16).padStart(64, '0')
  }

  // HMAC-SHA256签名
  hmacSha256(data, key) {
    // 简化的HMAC-SHA256实现
    const innerKey = key.length > 64 ? this.sha256(key) : key.padEnd(64, '\0')
    const outerKey = key.length > 64 ? this.sha256(key) : key.padEnd(64, '\0')
    
    const innerData = innerKey + data
    const outerData = outerKey + this.sha256(innerData)
    
    return this.sha256(outerData)
  }

  // 生成随机字符串
  generateNonce(length = 16) {
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
    let result = ''
    for (let i = 0; i < length; i++) {
      result += chars.charAt(Math.floor(Math.random() * chars.length))
    }
    return result
  }

  // 生成时间戳
  generateTimestamp() {
    return new Date().toISOString()
  }

  // 生成日期字符串（YYYYMMDD格式）
  generateDateString(timestamp) {
    return timestamp.substring(0, 8)
  }

  // 构建规范请求字符串
  buildCanonicalRequest(method, uri, headers, payload) {
    const canonicalHeaders = Object.keys(headers)
      .sort()
      .map(key => `${key.toLowerCase()}:${headers[key].trim()}`)
      .join('\n') + '\n'

    const signedHeaders = Object.keys(headers)
      .map(key => key.toLowerCase())
      .sort()
      .join(';')

    const hashedPayload = this.sha256(payload || '')

    return [
      method,
      uri,
      '', // 查询字符串（空）
      canonicalHeaders,
      signedHeaders,
      hashedPayload
    ].join('\n')
  }

  // 构建待签名字符串
  buildStringToSign(algorithm, timestamp, scope, hashedRequest) {
    return [
      algorithm,
      timestamp,
      scope,
      hashedRequest
    ].join('\n')
  }

  // 计算签名
  calculateSignature(stringToSign, date, region, service, secretKey) {
    const kDate = this.hmacSha256(date, `AWS4${secretKey}`)
    const kRegion = this.hmacSha256(region, kDate)
    const kService = this.hmacSha256(service, kRegion)
    const kSigning = this.hmacSha256('aws4_request', kService)
    
    return this.hmacSha256(stringToSign, kSigning)
  }

  // 生成AWS4签名认证头
  generateAuthHeader(accessKeyId, date, region, service, signedHeaders, signature) {
    const credential = `${accessKeyId}/${date}/${region}/${service}/aws4_request`
    return `AWS4-HMAC-SHA256 Credential=${credential}, SignedHeaders=${signedHeaders}, Signature=${signature}`
  }
}

module.exports = new CryptoHelper()
